/*
 *  Class name: AccountServiceImpl.java
 *  Version: 1.0
 *  Date: 22.6.2014
 */

package cz.morosystems.personwebmanager.businesslayer.sevices.impl;

import cz.morosystems.personwebmanager.businesslayer.sevices.AccountService;
import cz.morosystems.personwebmanager.persistencelayer.daos.AccountDAO;
import cz.morosystems.personwebmanager.persistencelayer.daos.UserDAO;
import cz.morosystems.personwebmanager.persistencelayer.entities.Account;
import cz.morosystems.personwebmanager.persistencelayer.entities.User;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import jdk.nashorn.internal.runtime.UserAccessorProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Michal Ďuriš
 */
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    
    @Autowired
    private AccountDAO accountManager;
    
    @Autowired
    private UserDAO userManager;

    public AccountServiceImpl() {
    }

    public void setAccountManager(AccountDAO accountManager) {
        this.accountManager = accountManager;
    }

    @Override
    public void addUsersAccount(Long userID, Account account) {
        
        User user = userManager.getUserByID(userID);
        
        user.getAccounts().add(account);
        
        userManager.changeUser(user);
    }
    

    @Override
    public void deleteUsersAccount(Long userID, Long accountID) {
        
        User user = userManager.getUserByID(userID);
        Account account = accountManager.getAccountByID(accountID);
        
        for (Iterator<Account> it = user.getAccounts().iterator(); it.hasNext();) {
            Account lazyAccount = it.next();
            
            if(Objects.equals(account.getId(), lazyAccount.getId())) {
                it.remove();
                break;
            }
        }
        
        if(Objects.equals(user.getPreferredAccount(), account)) {
            user.setPreferredAccount(null);
        }
        
        userManager.changeUser(user);
    }

    @Override
    public void changeAccount(Account account) {
        
        accountManager.changeAccount(account);
    }

    @Override
    public void deleteAccount(Long accountID) {
        
        accountManager.deleteAccount(accountID);
    }

    @Override
    public Account getAccountByID(Long accountID) {
        
        return accountManager.getAccountByID(accountID);
    }
    
}
